package com.hmall.order.Itemlistener;

import com.hmall.common.Client.ItemClient;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.impl.OrderDetailService;
import com.hmall.order.service.impl.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class ItemMqlistener {

    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderService orderService;
    @Autowired
    private IOrderDetailService orderDetailService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = "delay.queue", durable = "true"),
                    exchange = @Exchange(name = "delay.exchange", delayed = "true"),
                    key = "delay"
            )
    )
    public void listenOrder(String msg) {
        long orderId = Long.parseLong(msg);
        Order order = orderService.getById(orderId);

        Integer status = order.getStatus();
        //订单状态,1、未付款 2、已付款,未发货 3、已发货,未确认 4、确认收货，交易成功 5、交易取消，订单关闭 6、交易结束
        if (status != 1 && status != 5) {
            log.info("====监听到有效订单,orderId:{},orderDetail:{}", orderId, order);
            return;
        }
        log.info("====监听到无效订单===orderId:{}", orderId);
        // 关闭订单
        orderService.updateStatus(orderId);
        OrderDetail orderDetail = orderDetailService.getByOrderId(orderId);
        Integer num = orderDetail.getNum();
        //交易取消恢复库存
        itemClient.addStock(orderDetail.getItemId(), num);

    }
}





